import express from "express";
import fs from "fs/promises";
import path from "path";

const router = express.Router();
const LOGS_DIR = path.join(process.cwd(), "backend", "logs");

router.get("/", async (req, res) => {
  try {
    const files = await fs.readdir(LOGS_DIR);
    const logFiles = files
      .filter((file) => file.endsWith(".log"))
      .sort()
      .reverse();
    const logData = [];
    for (const file of logFiles.slice(0, 10)) {
      const filePath = path.join(LOGS_DIR, file);
      const content = await fs.readFile(filePath, "utf8");
      const lines = content.trim().split("\n");
      const entries = [];
      for (const line of lines) {
        try {
          entries.push(JSON.parse(line));
        } catch (parseError) {
          // 跳过无效日志行
        }
      }
      logData.push({
        date: file.replace(".log", ""),
        entries,
      });
    }
    res.json({ success: true, logs: logData });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

export default router;
